"""进度追踪路由"""
from fastapi import APIRouter
from typing import Dict, Any, Optional
from app.services.progress_service import progress_service

router = APIRouter()


@router.get("/progress/overview/{user_id}")
async def get_progress_overview(user_id: str):
    """获取进度概览"""
    overview = await progress_service.get_overview(user_id)
    return overview


@router.get("/progress/performance/{user_id}")
async def get_performance_metrics(user_id: str, period: Optional[str] = "week"):
    """获取性能指标（从真实数据计算）"""
    from datetime import datetime, timedelta
    from app.core.database import RedisClient
    import json
    
    redis = None
    try:
        redis = RedisClient.get_client()
        redis.ping()
    except:
        pass
    
    # 计算时间范围
    if period == "week":
        days = 7
    elif period == "month":
        days = 30
    else:
        days = 7
    
    end_date = datetime.now().date()
    start_date = end_date - timedelta(days=days)
    
    daily_stats = []
    total_questions = 0
    total_correct = 0
    total_time = 0
    
    if redis:
        try:
            # 获取指定时间范围内的记录
            current_date = start_date
            while current_date <= end_date:
                date_str = current_date.strftime("%Y-%m-%d")
                record_key = f"daily_record:{user_id}:{date_str}"
                
                if redis.exists(record_key):
                    records = redis.hgetall(record_key)
                    day_questions = 0
                    day_correct = 0
                    day_time = 0
                    
                    for qid, record_str in records.items():
                        try:
                            if isinstance(record_str, bytes):
                                record_str = record_str.decode('utf-8')
                            record = json.loads(record_str) if isinstance(record_str, str) else record_str
                            day_questions += 1
                            total_questions += 1
                            if record.get("is_correct", False):
                                day_correct += 1
                                total_correct += 1
                            # 时间估算：每题2.5分钟
                            day_time += 2.5
                            total_time += 2.5
                        except:
                            pass
                    
                    if day_questions > 0:
                        daily_stats.append({
                            "date": date_str,
                            "questions_answered": day_questions,
                            "correct_answers": day_correct,
                            "accuracy": round((day_correct / day_questions * 100), 1),
                            "study_duration": round(day_time, 0)
                        })
                
                current_date += timedelta(days=1)
        except Exception as e:
            print(f"Redis操作失败: {e}")
    
    # 计算平均指标
    accuracy_rate = (total_correct / total_questions * 100) if total_questions > 0 else 0
    average_time = (total_time / total_questions) if total_questions > 0 else 0
    
    # 计算改进率（对比第一周和最后一周）
    improvement_rate = 0.0
    if len(daily_stats) >= 7:
        first_week_avg = sum([s["accuracy"] for s in daily_stats[:3]]) / min(3, len(daily_stats))
        last_week_avg = sum([s["accuracy"] for s in daily_stats[-3:]]) / min(3, len(daily_stats))
        improvement_rate = last_week_avg - first_week_avg
    
    return {
        "user_id": user_id,
        "period": period,
        "metrics": {
            "accuracy_rate": round(accuracy_rate, 1),
            "average_time_per_question": round(average_time, 0),
            "thinking_quality_score": round(accuracy_rate * 0.9 + 10, 1),  # 基于准确率估算
            "improvement_rate": round(improvement_rate, 1)
        },
        "daily_stats": daily_stats
    }


@router.get("/progress/visualization/{user_id}")
async def get_visualization_data(user_id: str):
    """获取可视化数据"""
    visualization = await progress_service.get_visualization_data(user_id)
    return visualization


@router.get("/progress/weakness/{user_id}")
async def get_weakness_analysis(user_id: str):
    """获取薄弱环节分析"""
    weakness = await progress_service.get_weakness_analysis(user_id)
    return weakness


@router.get("/progress/achievements/{user_id}")
async def get_achievements(user_id: str):
    """获取成就列表（从真实数据计算）"""
    from app.core.database import RedisClient
    from app.services.user_onboarding_service import user_onboarding_service
    from datetime import datetime
    
    achievements = []
    
    # 获取用户状态
    user_status = user_onboarding_service.get_user_status(user_id)
    
    # 获取进度概览
    overview = await progress_service.get_overview(user_id)
    
    # 检查各种成就
    # 1. 初出茅庐 - 完成首次评估
    if user_status.get("has_completed_test"):
        achievements.append({
            "achievement_id": "ach_001",
            "name": "初出茅庐",
            "description": "完成首次评估",
            "unlocked_at": datetime.now().isoformat(),
            "icon": "🎯"
        })
    
    # 2. 坚持不懈 - 连续学习5天
    if overview.get("current_streak", 0) >= 5:
        achievements.append({
            "achievement_id": "ach_002",
            "name": "坚持不懈",
            "description": f"连续学习{overview.get('current_streak', 0)}天",
            "unlocked_at": datetime.now().isoformat(),
            "icon": "🔥"
        })
    
    # 3. 精准打击 - 准确率超过80%
    if overview.get("overall_accuracy", 0) >= 80:
        achievements.append({
            "achievement_id": "ach_003",
            "name": "精准打击",
            "description": f"总体准确率{overview.get('overall_accuracy', 0):.1f}%",
            "unlocked_at": datetime.now().isoformat(),
            "icon": "🎯"
        })
    
    # 4. 百题达人 - 答题总数超过100
    if overview.get("total_questions", 0) >= 100:
        achievements.append({
            "achievement_id": "ach_004",
            "name": "百题达人",
            "description": f"累计答题{overview.get('total_questions', 0)}题",
            "unlocked_at": datetime.now().isoformat(),
            "icon": "📚"
        })
    
    # 5. 学习达人 - 学习天数超过10天
    if overview.get("total_study_days", 0) >= 10:
        achievements.append({
            "achievement_id": "ach_005",
            "name": "学习达人",
            "description": f"累计学习{overview.get('total_study_days', 0)}天",
            "unlocked_at": datetime.now().isoformat(),
            "icon": "⭐"
        })
    
    return {
        "user_id": user_id,
        "achievements": achievements,
        "total_unlocked": len(achievements),
        "total_available": 20
    }

